package com.cow.sram.comm.config.tree;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cow.framework.core.base.BaseComponent;
import com.cow.framework.utils.convert.ConvertUtil;
import com.cow.sram.data.dao.TreeDefDAO;
import com.cow.sram.data.entity.Resourceinfo;

/**
 * 树形参数管理服务
 * 
 * @author yangsj
 */
@Service
public class TreeDefService extends BaseComponent{
	@Autowired
	TreeDefDAO treeDefDAO;
	
	/**查询树形参数*/
	public Resourceinfo getTreeDefById(Integer id){
		return  treeDefDAO.findOne(id);
	}
	
	/**保存树形参数*/
	public Resourceinfo saveTreeDef(Resourceinfo treeDef){
		return treeDefDAO.save(treeDef);
	}

	/**删除树形参数*/
	public void delTreeDefById(Integer id){
		treeDefDAO.delete(id);
	}
	/**新增节点缓存*/
	public void addTreeNodeCache(Resourceinfo node){
		//更新缓存
		List<Resourceinfo> treeList = (List<Resourceinfo>)redisUtil.get("treeDef-"+node.getResourcetype()+"-"+ConvertUtil.nvl(node.getFatherId(),"")); 
		if(treeList == null){
			treeList = new ArrayList<Resourceinfo>();					
		}
		treeList.add(node);
		redisUtil.set("treeDef-"+node.getResourcetype()+"-"+node.getFatherId(),treeList); 
	}
	/**删除节点缓存*/
	public void delTreeNodeCache(Resourceinfo node){
		//更新缓存
		List<Resourceinfo> treeList = (List<Resourceinfo>)redisUtil.get("treeDef-"+node.getResourcetype()+"-"+ConvertUtil.nvl(node.getFatherId(),"")); 
		if(treeList != null){
			for(int i = 0;i < treeList.size(); i++){
				Resourceinfo t = treeList.get(i);
				if(node.getResourceid().equals(t.getResourceid())){
					treeList.remove(i);
					break;
				}
			}
			
			if(treeList.size() > 0){
				redisUtil.set("treeDef-"+node.getResourcetype()+"-"+node.getFatherId(),treeList); 
			}else{
				redisUtil.remove("treeDef-"+node.getResourcetype()+"-"+node.getFatherId());
			}
		}
	}
	/**修改节点缓存*/
	public void updateTreeNodeCache(Resourceinfo node){
		//更新缓存
		List<Resourceinfo> treeList = (List<Resourceinfo>)redisUtil.get("treeDef-"+node.getResourcetype()+"-"+ConvertUtil.nvl(node.getFatherId(),"")); 
		if(treeList == null){
			treeList = new ArrayList<Resourceinfo>();					
		}
		for(int i = 0;i < treeList.size(); i++){
			Resourceinfo t = treeList.get(i);
			if(node.getResourceid().equals(t.getResourceid())){
				treeList.set(i, node);
				break;
			}
		}
		
		redisUtil.set("treeDef-"+node.getResourcetype()+"-"+node.getFatherId(),treeList); 
	}
}
